;(function () {
  window.vueMethod = new Vue({
    el: '#workingGroup',
    data: {
      page: {
        num: 0,
        list: [10,15,20]
      },
      params: {
        keyword: null,
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
        totalCount: 0
      },
      wgData: [],
      addFlag:false,
      editFlag:false,
      deleteFlag:false,
      rperson: {
        ids: [],
        name: null,
        list: []
      },       // 对接人
      nodeUser: [],
      groupId: null
    },
    filters: {
      lot: function (arr) {
        var arr2 = [];
        function findInArr(item,arr) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == item) {
                    return true;
                }
            }
            return false;
        }
        for (var i = 0; i < arr.length; i++) {
            if (!findInArr(arr[i],arr2)) {
                arr2.push(arr[i]);
            }
        }
        return arr2.length;
      }
    },
    methods: {
      //输入对接人进行搜索
      onInputDJR: function () {
        this.fzrDropdown()
        $('.append-temp').css('display', 'block')
      },
      // 匹配负责人
      fzrDropdown:function(){
        var self = this;
        hlhttp.get({
          url:'tenants/users/_search',
          data:{keyword:self.params.keyword},
          success:function(data){
            self.rperson.list = data;
          }
        })
      },
      // 删除人员
      delperson (i) {
        this.nodeUser.splice(i, 1)
        approve.data.selectPerson = this.nodeUser;
        approve.dom.showRight()
      },
      //设置对接人name，获取id
      setRperson: function (name) {
        this.params.keyword = name;
        document.querySelector('.append-temp').style.display = 'none';
      },
      search(){
        this.params.currentPage = 1
        this.getData()
      },
      //获取列表
      getData() {
        var _this = this;

        hlhttp.get({
          url: 'data_groups/_search',
          data: {
            keyword: _this.params.keyword || '#',
            page: _this.params.currentPage,
            page_size: _this.params.pageSize
          },
          success: function (res) {
            _this.params.totalCount = res.totalCount
            _this.params.totalPage = res.totalPage
            _this.wgData = res.dataGroupList

          }
        })
      },
      //设置页数
      pageSelect: function (num) {
        this.params.pageSize = num
        this.params.currentPage = 1
        this.getData()
      },
      //重置
      resetButton: function () {
        this.params.keyword = null
        this.params.currentPage = 1
        this.rperson = {
          ids: [],
          name: null,
          list: []
        };
        this.getData()
      },
      //删除某个列表
      delteList: function (id) {
        var _this = this;

        hllayer.confirm('删除后负责人无法再看到组员的业务数据！', function () {
          hlhttp.delete({
            url: 'data_group?data_group_id=' + id,
            success: function () {
              hl.toast('删除成功')
              _this.getData()
            }
          })
        })
      },
      // 查看工作组
      checkGroup: function (id, userIds) {
        var self = this
        var permissions = window.localStorage.getItem('permissions')
        this.groupId = id;
        if(permissions.indexOf('c77') >= 0){
          $('.save-wkp').show()
        }else{
          $('.save-wkp').hide()
        }
        $('.wkp-pop').show()
        $('.backdrop').show()

        hlhttp.get({
          url:'data_group/' + id + '/info,user_info',
          success:function(data){
            $('.grp-ipt').val(data.name)
            $('.fzr').val(data.leaderName)
            $('.fzr').attr('data-name',data.leaderName).attr('data-id',data.leaderId).attr('data-tel',data.leaderPhone)
            self.nodeUser = []
            if(data.users.length !== 0){
              data.users.map(function(_item){
                self.nodeUser.push({id: _item.userId, name: _item.userName, account: _item.userAccount, phone: _item.userPhone})
              })
              approve.data.selectPerson = self.nodeUser;
            }else{
              $('.no-member').show()
            }

          }
        })

      },
      saveEdit:function(){
        if(!this.validateWorking())return
        var self = this;
        let users = [];
        self.nodeUser.map(item => {
          users.push(item.id)
        })
        var data = {
          id: this.groupId,
          name:$('.grp-ipt').val().trim(),
          leader_id:$('.fzr').attr('data-id'),
          leader_name:$('.fzr').attr('data-name'),
          leader_phone:$('.fzr').attr('data-tel'),
          user_ids: users.join(',')
        }

        hlhttp.put({
          url:'data_group',
          headers:{token:Cookies.get("token")},
          data:data,
          success:function(data){
            hl.toast('编辑成功')
            $('.wkp-pop').hide()
            $('.backdrop').hide()
            self.getData()
            approve.methods.detailList(approve.data.initId, $('.approve-bottom'), true)
          }
        })
      },
      // 新建保存
      saveCreate:function(){
        var self = this;
        if(!self.validateWorking())return
        let users = [];
        self.nodeUser.map(item => {
          users.push(item.id)
        })
        var data = {
          name:$('.grp-ipt').val().trim(),
          leader_id:$('.fzr').attr('data-id'),
          leader_name:$('.fzr').attr('data-name'),
          leader_phone:$('.fzr').attr('data-tel'),
          user_ids:users.join(',')
        }

        hlhttp.post({
          url:'data_group',
          data:data,
          success:function(data){
            hl.toast('新建成功')
            $('.wkp-pop').hide()
            $('.backdrop').hide()
            self.getData()
            approve.methods.detailList(approve.data.initId, $('.approve-bottom'), true)
          }
        })
      },
      // 保存验证
      validateWorking:function(){
        if(!$('.grp-ipt').val().trim()){
          hl.toast('工作组名称不能为空')
          return false;
        }
        if(!$('.fzr').val()){
          hl.toast('负责人名称不能为空')
          return false;
        }
        if(!$('.fzr').attr('data-id')){
          hl.toast('请填写用户中存在的负责人')
          $(this).val('')
          return false;
        }
        return true;
      },
      // 新增工作组
      addGroup:function(){
        this.nodeUser = []
        this.groupId = null;
        $('.save-wkp').show()
        $('.wkp-pop').show()
        $('.backdrop').show()

      },
      // 权限
      getPermissions:function(){
        var self = this
        var permissions = window.localStorage.getItem('permissions')
        if(permissions.indexOf('c76') >= 0){ self.addFlag = true }
        if(permissions.indexOf('c78') >= 0){self.deleteFlag = true}
      },
      saveSelect () {
        this.users = JSON.parse(JSON.stringify(this.nodeUser))
        this.hideSelectPerson()
      },
      hideSelectPerson () {
        $('.wkp-pop').hide()
        $('.backdrop').hide()
      },
      //匹配负责人
      inputfzr () {
        var self = this;
        var sendUsersSearchRequest = function(val){
          hlhttp.get({
            url:'tenants/users/_search',
            data:{keyword:val},
            success:function(data){
              var html = '';
              data.map(function(_item){
                html += '<li data-id="' + _item.id + '"><i class="name">' + _item.name + '</i><i class="tel">'+  _item.phone + '</i></li>'
              })
              $('.fzr-ipt-select ul').html(html).show()
              // 如果自己输入的名字  则匹配对应的id
              if(data.length !== 0){
                data.map(function(_item){
                  if(_item.name == val || _item.phone == val){
                    $('.fzr').attr('data-name',_item.name)
                             .attr('data-tel',_item.phone)
                             .attr('data-id',_item.id)
                  }
                })
                var html = '';
                data.map(function(_item){
                  html += '<li data-id="' + _item.id + '"><i class="name">' + _item.name + '</i><i class="tel">'+  _item.phone + '</i></li>'
                })
                $('.fzr-ipt-select ul').html(html).show()
              }else{
                $('.fzr').attr('data-name','')
                         .attr('data-tel','')
                         .attr('data-id','')
              }
            }
          })
        }

        $('.fzr').bind('input',function(){
          var value = $(this).val().trim()
          window.setTimeout(function(){
            sendUsersSearchRequest(value)
          },150)
        })
        $('.fzr').bind('blur',function(){
          if(!$('.fzr').attr('data-name')){$('.fzr').val('')}
        })
        $('.fzr-ipt-select').on('click','li',function(){
          $('.fzr').val($(this).find('.name').text())
          $('.fzr').attr('data-name',$(this).find('.name').text())
                   .attr('data-tel',$(this).find('.tel').text())
                   .attr('data-id',$(this).attr('data-id'))
          $('.fzr-ipt-select ul').hide()
        })
        $(document).click(function(){
          $('.fzr-ipt-select ul').hide()
        })
      }
    },
    mounted: function () {
      this.getData()
      this.getPermissions()
      hlSelectUi()
      this.inputfzr()

      approve.dom.addinitialDom()
      approve.event.wxddNodeEvent((data) => {
        this.nodeUser = data;
      })

      $(document.body).click(function(event) {
        $('.append-temp').css('display', 'none')
      });
    }
  })
} ())
